﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KZ400B
{
    public partial class AxleManager
    {
        /// <summary>
        /// 查询当前位置
        /// </summary>
        /// <param name="axleName"></param>
        /// <returns></returns>
        protected static bool QueryOneAxlePosition(
        string axleName
        ,ref double position
        )
        {
            position = 0.0F;
            if (!IsOpen)
            {
                return false;
            }

            string data = Protocol.Packet(
                Protocol.GetQueryPostionString(axleName)
                );
            
            return sendData(data);

            /*
            bool commError = false;
            bool ack = false;
            try
            {
                double dpos = 0.0F;
                string msg = string.Empty;
                lock (s_spLocker)
                {
                    if (spLink == null) { return false; }
                    if (spLink.CanWrite)
                    {
                        spLink.Write(data);
                        msg = spLink.ReadString(2);

                        if (string.IsNullOrEmpty(msg))
                        {
                            return false;
                        }
                        bool repRst = handleNrmAck(FunctionCode.FCodeQuery, axleName, msg, false)
                            == CommResultCode.Success
                            ;

                        long id = createMsgId();
                        if (repRst)
                        {
                            
                            while (isCommRunning() && !ack)
                            {
                                if (String.IsNullOrEmpty(msg))
                                {
                                    msg = spLink.ReadString(1);
                                }
                                UnpacketResult uRst = Protocol.Unpack(msg);
                                if (!uRst.Result || string.IsNullOrEmpty(uRst.Content))//通讯异常
                                {
                                    commError = true;
                                    break;
                                }
                                else if (uRst.CommFlag.Equals(CommFlag.Query))
                                {
                                    string aName = uRst.Content[0].ToString();
                                    string aP = uRst.Content.Substring(1);
                                    Axle t_Axle = null;
                                    if (!string.IsNullOrEmpty(aName) && !string.IsNullOrEmpty(aP))
                                    {
                                        int aPos = 0;
                                        t_Axle = AxleCacheManager.getAxle(aName);
                                        if (t_Axle != null && int.TryParse(aP, out aPos))
                                        {
                                            t_Axle.Position = aPos;
                                            dpos = t_Axle.DisplayPosition;
                                            //t_Axle.Position = Axle.ComputeRelativePosition(aPos, t_Axle.RelativeZero);

                                            position = aPos;
                                            //
                                            //if (OnAxlePostionChange != null)
                                            //{
                                            //    OnAxlePostionChange(axleName, t_Axle, dpos);
                                            //}
                                            PositionCacheManager.ChangePosition(axleName, dpos);
                                            PositionCacheManager.SubmitChange(axleName, true);
                                            ack = true;
                                        }
                                    }
                                    
                                }
                                else
                                {
                                    addRecvMsg(id, msg);
                                    
                                }
                                msg = string.Empty;
                            }
                        }// response is right
                    }// can write
                }//lock



                if (ack )
                {
                    KZ400B.Data.AxleStateBarMsg.Instance.AxleState = string.Format("[{0}] 轴 位置: {1} ", axleName, dpos);
                    return true;
                }
                
            }
            finally
            {
                //setIsLocked(false);
            }

            if (commError)
            {
                KZ400B.Data.AxleStateBarMsg.Instance.AxleState = "读取到错误帧,请检查通讯链路";
            }
            
            return false;
             */
        }

        public static bool QueryPosition(
        string axleName
        )
        {
            double ps = 0.0F;
            bool rst = QueryOneAxlePosition(axleName, ref ps);
            return rst;
        }

        public static bool QueryPositionIM(string axleName)
        {
            double ps = 0.0F;
            bool rst = QueryOneAxlePosition(axleName, ref ps);
            if (rst)
            {
                lock (s_spLocker)
                {
                    if (spLink.CanRead)
                    {
                        string msg = spLink.ReadString(5);
                        if (string.IsNullOrEmpty(msg))
                        {
                            return false;
                        }
                        ProtocolV2.UnpacketResult ur = ProtocolV2.Unpack(msg);
                        rst = ur.Result && ur.Action == AxleActions.QueryPositionRespond;
                        if (!rst)
                        {
                            return rst;
                        }
                        OnQueryPositionRespond(ur);

                         msg = spLink.ReadString(5);
                        if (string.IsNullOrEmpty(msg))
                        {
                            return false;
                        }
                        ur = ProtocolV2.Unpack(msg);
                        rst = ur.Result && ur.Action == AxleActions.QueryPositionFinish;
                        if (!rst)
                        {
                            return false;
                        }
                        OnQueryPositionComplete(ur);
                        return true;
                    }
                }// link lock
            }
            return false;
        }

         static void OnQueryPositionRespond(ProtocolV2.UnpacketResult ur)
        {
            if (ur.Result
                    && ur.Action == AxleActions.QueryPositionRespond

                    )
            {
                if (AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
                {
                    //AxleCacheManager.AxleList[ur.AxleName].AxleStatus = AxleStatus.Running;
                }
            }

            setState(
                string.Format("[{0}] 轴 查询位置命令响应 : {1} {2} "
                        , ur.AxleName
                        , ur.Result ? "正确" : "错误"
                        , ur.Result ? "-> 查询位置运行中 ... " : string.Empty
                        )
            );
        }

         static void OnQueryPositionComplete(ProtocolV2.UnpacketResult ur)
        {
            if (ur.Result
                && ur.Action == AxleActions.QueryPositionFinish

                )
            {
                if (AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
                {
                    AxleCacheManager.AxleList[ur.AxleName].Position = ur.Position;
                    double dpos = AxleCacheManager.AxleList[ur.AxleName].DisplayPosition;

                    PositionCacheManager.ChangePosition(ur.AxleName, dpos);
                    PositionCacheManager.SubmitChange(ur.AxleName, ur.Result);

                    setState(
                        string.Format("[{0}] 轴 查询位置命令运行结束 : {1}"
                                , ur.AxleName
                                , dpos.ToString(MySetting.PositionDisDeciFormatter)
                                )
                    );
                    AxleCacheManager.Update(ur.AxleName);
                }

            }

        }
    }
}
